﻿// LdmInstruction.cs
// Load  Multiple instruction class. 

using System;


namespace armsim
{
    /// <summary>
    /// Class for an LDM instruction in an Arm architecture
    /// </summary>
    public class LdmInstruction : LoadStoreMultipleInstruction
    {

        /// <summary>
        /// Initializes a new LdmInstruction
        /// </summary>
        /// <param name="instruction">the LdmInstruction is encoded from this 32 bit encoded instruction</param>
        public LdmInstruction(uint instruction)
            : base(instruction)
        {
        }

        /// <summary>
        /// Exectures the LDM instruction
        /// </summary>
        /// <param name="cpu">location containing the registers to load into</param>
        public override void Execute(VirtualCPU cpu)
        {
            var address = cpu.Registers.ReadRegistersDuringExecute(VirtualMemory.MapRegNoToRegMem(this.Rn));
            for (uint i = 0; i < 16u; ++i)
            {
                if (this.RegisterList.RegBoolList[i] == true)
                {
                    cpu.Registers.WriteWord(VirtualMemory.MapRegNoToRegMem(i), cpu.RAM.ReadWord(address));
                    address += 4;
                }

            }

            if (this.W == 1u)
            {
                cpu.Registers.WriteWord(VirtualMemory.MapRegNoToRegMem(this.Rn), address);
            }

        }

        /// <summary>
        /// Constructs an assembly string of the instruction
        /// </summary>
        /// <param name="cpu">central processing unit</param>
        /// <returns>string of the assembly code for the instruction</returns>
        public override string ToAssembly(VirtualCPU cpu)
        {
            return String.Format("LDMFD {0}", base.ToAssembly(cpu));

        }


    }
}
